<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.03.30
 */

namespace App\Controller\Http;

use App\Constants\Constants;
use App\Controller\AbstractController;
use App\Library\Traits\Helper;
use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;

class LoginController extends AbstractController
{
    use Helper;

    /**
     * @Inject
     * @var  UserService
     */
    protected $service;

    public function login()
    {
        try {
            $rules = [
                'account'  => 'required',
                'password' => 'required',
            ];
            $this->validator($rules);
            $data   = $this->combine(array_keys($rules));
            $result = $this->service->login($data);
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), $result);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }

    public function logout()
    {
        try {
            $token = $this->request->input(Constants::TOKEN) ?? ($this->request->header(Constants::X_TOKEN) ?? '');
            if (!$token) {
                throw new \ErrorException(t('message.12044'));
            }
            $result = $this->service->logout($token);
            return $this->response->showResults(Constants::RETURN_SUCCESS, t('message.12001'), $result);
        } catch (\Exception $exception) {
            return $this->response->showResults(Constants::SERVER_ERROR, $exception->getMessage(), []);
        }
    }
}
